﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace Game.System.EventSystem.EventWindow
{
    /// <summary>
    /// 事件图窗口
    /// </summary>
    public class EventGraphWindow : EditorWindow
    {
        // 节点视窗
        private static EventGranphView m_View;

        //打开窗口
        public static void OpenWindow(EventGraph graph)
        {
            EventGraphWindow window = GetWindow<EventGraphWindow>("Event Graph");
            window.minSize = new Vector2(800, 600);
            window.Show();

            m_View = new EventGranphView(window, graph);
        }

        private void OnGUI()
        {
            
            ProcessEvent();

            //绘制内容写在BeginWindows和EndWindows中间
            BeginWindows();
            m_View.Draw();
            EndWindows();
        }

        //处理鼠标点击
        private void ProcessEvent()
        {
            Event e = Event.current;
            Vector2 mousePos = e.mousePosition;

            //右键按下
            if (e.button == 1 && e.type == EventType.MouseDown)
            {
                //如果点击Node
                if (m_View.ClickOnNode(mousePos, out BaseEventNode node))
                {
                    //创建菜单
                    GenericMenu menu = new GenericMenu();
                    if (node is EventGroupNode)
                    {
                        menu.AddItem(new GUIContent("添加事件"), false, m_View.AddNode<SingleEventNode>, node);
                        menu.AddItem(new GUIContent("添加事件组"), false, m_View.AddNode<EventGroupNode>, node);
                        if (node.eventName == "Root")
                        {
                            //不能删除Root节点
                            menu.AddDisabledItem(new GUIContent("删除"));
                        }
                        else
                        {
                            menu.AddItem(new GUIContent("删除"), false, m_View.DeleteNode, node);
                        }
                    }
                    else if (node is SingleEventNode)
                    {
                        menu.AddItem(new GUIContent("删除"), false, m_View.DeleteNode, node);
                    }
                    menu.ShowAsContext();
                    e.Use();
                }
            }
            //左键
            else if (e.button == 0 && e.type == EventType.MouseDrag)
            {
                //没有点中节点则整体移动
                if (!m_View.ClickOnNode(mousePos, out BaseEventNode node))
                {
                    m_View.Move(e.delta);
                }
                else
                {
                    node.MoveNode(e.delta);
                }
            }
        }

        private void OnDisable()
        {
            m_View.SaveData();
            m_View = null;
        }
    }
}
